<?php
/**
 * 当天北京时间7点返回维也纳时间前一天的数据
 * 北京时间7月25日7点返回维也纳时间（东一区） 7月24号的数据（北京时间7月24日7：00-北京时间7月25日7：00）
 * 获取通道返回数据模块
 */
namespace app\controllers\crontab;
use Yii;
use app\components\Sftp;
use app\components\EmailMarket;
use app\components\msgcenter\MsgCenter;
use app\components\redis\RedisSysEmail;

class GetEmarsysChannelReturnDataController extends \app\base\Controller
{
    
    public $config = array(
        'host'      => 'e3.emarsys.net',
        'user'      => 'dest',
        'port'      => '22',
        'passwd'    => 'RhkLN4hH',
    );
    // 到达通道商的所有数据
    public $reachChannelDataArr = [];
    public $emailObj;
    public $downLoadFileName = ""; 
    public $FileUnZipName = "";
    public $dirPath = ROOT_PATH.'/bounces_data/emarsys_data/';
    public $msg ='';
    public $key = 'get_detail_info';
    public $channel = 'emarsys';

    /**
     * 检查工作环境条件是否满足,如果工作环境条件不满足，则进行终止后面业务分析
     * @author Ken
     * @date 2015/12/22
     * 
     */
    public function checkEnvironment()
    {
        // 检查函数是否可用
        $checkFunctionList = array('shell_exec');
        
        // 定义常量,默认环境正常
        $isFunWork = true;
        $needToInstallList = '';                                // 存储未满足条件的环境变量
        
        // 遍历检查函数情况
        foreach($checkFunctionList as $key => $value)
        {
            if(!function_exists($value))
            {
                $isFunWork = false;                             // 设置环境变量不满足
                $needToInstallList = $value;                    // 存储不满足条件的原因
                break;                                          // 跳出检测
            }
        }
        
        // 判断是否满足工作环境
        if(!$isFunWork)
        {
            echo 'PHP工作环境缺少 ',$needToInstallList,' 请进行环境安装确认！';
            exit;
        }
    }


    /**
     * 下载文件
     */
    public function downLoadFile()
    {
        if (isset($_GET['curBjTime']) && $_GET['curBjTime']) {
            $curBjTime = $_GET['curBjTime'];
        } else {
            $curBjTime = \yii::$app->bjTime->time();
        }
       
        
        $curDay =\yii::$app->bjTime->date("Ymd",$curBjTime);
        $beforeOneDay = \yii::$app->bjTime->date("Ymd",$curBjTime-24*3600);
        
       
        // 当前要下载的文件名
       $this->downLoadFileName = $beforeOneDay.'000000_TO_'.$curDay.'000000.zip'; 
       $this->FileUnZipName = $beforeOneDay.'000000_TO_'.$curDay.'000000'; 
       
       if (!file_exists(ROOT_PATH.'/bounces_data') || !is_dir(ROOT_PATH.'/bounces_data')) { // 说明目录不存在
           $this->msg = ROOT_PATH.'/bounces_data 目录不存在请手动创建';
           echo  $this->msg;
           return false;
        } else { // 创建相关文件夹
            if (!file_exists($this->dirPath)) {
                mkdir($this->dirPath);
            }
            
            if (file_exists($this->dirPath.$this->FileUnZipName)) {
                $this->msg = $this->dirPath.$this->FileUnZipName.'已经解压成功';
                echo  $this->msg;
                return true;
            }
            
            if (file_exists($this->dirPath.$this->downLoadFileName)) {
                $this->msg =  $this->dirPath.$this->downLoadFileName.'已经存在';
                echo  $this->msg;
                return true; // 文件已经存在，直接处理，不需要再次下载
            }
        }
        
       
        
        // 连接sftp拉取文件
        //重连5次
        $times = 0;
        while ($times < 5) {
            try {
                $handle = new Sftp($this->config, false);//使用密码访问
                
            } catch (Exception $e) {
                echo '第'.($times+1).'次连接错误：'.$e->getMessage();
            }
            if(isset($handle) && true === $handle->active) {
                break;
            }
            $times++;
        }
        
        $fromRemoteZipFile = "exports/".$this->downLoadFileName;
        $toLocalZipPath = $this->dirPath.$this->downLoadFileName;
        // 下载文件
        echo '下载文件'.$this->downLoadFileName;
        $downloadResult = $handle->donwloadSftpZip($fromRemoteZipFile, $toLocalZipPath,$this->msg);
        
        return $downloadResult;
        
    }

    public function actionUnzip() {
        $params = $_REQUEST;
        $this->downLoadFileName = '20180704000000_TO_20180705000000.zip';
        $this->FileUnZipName = 'xian';
        if (!empty($params['downfilename'])) {
            $this->downLoadFileName = $params['downfilename'];
        }
        if (!empty($params['filename'])) {

            $this->FileUnZipName = $params['filename'];
        }
        $upZipFlag = $this->unZip();   // 解压
        var_dump($upZipFlag);
    }


    /**
     * 数据抓取
     */
    public function actionGetDetailInfo() 
    {
        ignore_user_abort(true);
        set_time_limit(0);
        $redis = new RedisSysEmail();
        echo "<pre/>";
        var_dump( $redis->get($this->key));
        if (isset($_REQUEST['type']) && $_REQUEST['type'] == 'open') {
            $redis->set($this->key.'status',\GuzzleHttp\json_encode(['status' => true,'number' => 1]));
            $redis->del($this->key);
        }
        $status = $redis->get($this->key.'status');
        $status = \GuzzleHttp\json_decode($status,true);
        var_dump($status);
        if (isset($status['status'],$status['number']) && (empty($status['status']) || $status['number'] >4 )) {
            exit("今天数据已经处理完...");
        }
        $number =$status['number'] +1;
        var_dump($number);
        $redis->set($this->key.'status',\GuzzleHttp\json_encode(['status' => true,'number' =>$number ]));

        // $this->checkEnvironment();
        $currentTime = date('Y-m-d',time());
        $msgCenter = new MsgCenter();
        $noticeInfo = [
            'site_id' => 99,
            'title' =>  "【EMP】【{$this->channel}】数据统计异常提示",
            'channel' => $this->channel,
            'exception_info' => '',   //异常详情
            'explain_info' => '',           //异常说明
            'monitor_id' => 0,   //监控项类型 0 => '全部',1=>'获取文件失败',2 => '下载文件失败',3=>'解压失败',4=>'数据更新异常'
            'monitor' => '',     //监控项
            'currentTime' => $currentTime
        ];
        $titleArr =['downloadfile' => '下载文件失败','unZip' => 'EMP解压数据文件失败','dealData' =>'通道返回数据写入mysql异常'];
        $monitor_type = ['downloadfile' => 1,'unZip' => 2,'dealData' =>3];

        $schedule = ['current' => 'downloadfile','syn_completed' => 'false','status'=>'false','msg' =>''];
        $json = $redis->get($this->key);
        $info = \GuzzleHttp\json_decode($json,true);

        if (! empty($info)) {

            if ( $status['number'] >3 )  {   //第一次失败，和重连三次后再失败就弹出提示
                $title = isset($titleArr[$info['current']]) ? $titleArr[$info['current']] : "没有匹配的错误信息";
                $msg = isset($info['msg']) ? $info['msg'] : '没有更多信息';
                $noticeInfo['title'] .= "【{$title}】";
                $noticeInfo['explain_info'] = $title;
                $noticeInfo['monitor'] = isset($titleArr[$info['current']]) ? $titleArr[$info['current']] : '';
                $noticeInfo['exception_info'] = $msg;
                $noticeInfo['exception_type'] = $msg;
                $noticeInfo['monitor_id'] = isset($monitor_type[$info['current']]) ? $monitor_type[$info['current']] : 0;
                $msgCenter->dealEmarysException($noticeInfo);
//                if ( $status['number'] == 4 ) {
//                    exit("失败3次后，停止执行");
//                }
                exit("失败3次后，停止执行");
            }

            switch ($info['current']) {
                case 'downloadfile' :
                    $downloadResult = $this->downLoadFile();
                    if (empty($downloadResult)) {
                        $schedule['msg'] =$this->msg;
                        $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
//                        $noticeInfo['title'] .=  "【{$titleArr['downloadfile']}】";
//                        $noticeInfo['explain_info'] = $noticeInfo['title'];
//                        $noticeInfo['monitor'] = $titleArr['downloadfile'];
//                        $noticeInfo['exception_info'] = $this->msg;
//                        $msgCenter->dealEmarysException($noticeInfo);
//                        $noticeInfo['monitor_id'] = 1;
//                        echo '--文件下载失败<br/>';
                        exit;
                    }

                case 'unZip'    :
                    $schedule['current'] ='unZip';
                    $schedule['msg'] ='EMP解压数据文件失败';
                    $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
                    $upZipFlag = $this->unZip();   // 解压
                    if (empty($upZipFlag)) {
                         $schedule['msg'] =$this->msg;
                         $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
//                        $noticeInfo['title'] .=  "【{$titleArr['unZip']}】";
//                        $noticeInfo['explain_info'] = $noticeInfo['title'];
//                        $noticeInfo['monitor'] = $titleArr['unZip'];
//                        $noticeInfo['exception_info'] = $this->msg;
//                        $noticeInfo['monitor_id'] = 2;
//                        $msgCenter->dealEmarysException($noticeInfo);
                        exit;
                    }

                case 'dealData' :
                    $schedule['current'] ='dealData';
                    $schedule['msg'] ='通道返回数据写入mysql异常';
                    $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
                    $dealDataRes = $this->dealData();
                    if (empty($dealDataRes)) {
                        $schedule['msg'] =$this->msg;
                        $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
//                        $noticeInfo['title'] .=  "【{$titleArr['dealData']}】";
//                        $noticeInfo['explain_info'] = $noticeInfo['title'];
//                        $noticeInfo['monitor'] = $titleArr['dealData'];
//                        $noticeInfo['exception_info'] = $this->msg;
//                        $noticeInfo['monitor_id'] =3;
//                        $msgCenter->dealEmarysException($noticeInfo);
                        exit;
                    }

                    echo '--数据处理完毕!<br>';
                    $redis->del($this->key);
//                    $redis->set($this->key.'status',false);   //数据已经处理完，关闭
                    $redis->set($this->key.'status',\GuzzleHttp\json_encode(['status' => false,'number' => 0]));   //数据已经处理完，关闭
                    break;
                default :
                    break;
            }
        }else {
            $schedule['current'] ='downloadfile';
            $schedule['msg'] ='文件下载失败';
            $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
            $downloadResult = $this->downLoadFile();
            if (empty($downloadResult)) {
                $schedule['msg'] = $this->msg;
                $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
//                $noticeInfo['title'] .=  "【emarsys 文件下载失败】";
//                $noticeInfo['explain_info'] = $noticeInfo['title'];
//                $noticeInfo['monitor'] = $titleArr['downloadfile'];
//                $noticeInfo['exception_info'] = $this->msg;
//                $noticeInfo['monitor_id'] =1;
//                $msgCenter->dealEmarysException($noticeInfo);
//                echo '--文件下载失败<br/>';
                exit;
            }
            echo '--文件下载成功<br/>';
            $schedule['current'] ='unZip';
            $schedule['msg'] ='EMP解压数据文件失败';
            $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
            $upZipFlag = $this->unZip();   // 解压

            if ($upZipFlag) {
                // 处理相关文件
                $schedule['current'] ='dealData';
                $schedule['msg'] ='通道返回数据写入mysql异常';
                $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
                $dealDataRes = $this->dealData();
                if (empty($dealDataRes)) {
                    $schedule['msg'] = $this->msg;
                    $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
//                    $noticeInfo['title'] .=  "【{$titleArr['dealData']}】";
//                    $noticeInfo['explain_info'] = $noticeInfo['title'];
//                    $noticeInfo['monitor'] = $titleArr['dealData'];
//                    $noticeInfo['exception_info'] = $this->msg;
//                    $noticeInfo['monitor_id'] =3;
//                    $msgCenter->dealEmarysException($noticeInfo);
                    exit;
                }
                echo '--数据处理完毕!';
                $redis->del($this->key);
//                $redis->set($this->key.'status',false);   //数据已经处理完，关闭
                $redis->set($this->key.'status',\GuzzleHttp\json_encode(['status' => false,'number' => 0]));   //数据已经处理完，关闭
                exit('done ...\n');
            }
            $schedule['msg'] = $this->msg;
            $redis->set($this->key,\GuzzleHttp\json_encode($schedule));
//            $noticeInfo['title'] .=  "【 emarsys 解压失败】";
//            $noticeInfo['explain_info'] = $noticeInfo['title'];
//            $noticeInfo['monitor'] = $titleArr['unZip'];
//            $noticeInfo['exception_info'] = $this->msg;
//            $noticeInfo['monitor_id'] = 2;
//            $msgCenter->dealEmarysException($noticeInfo);
        }

    }


    /**
     * 时间处理函数
     */
    public function timeDeal($timeS) {
       
        //file_put_contents(ROOT_PATH.'/upload/testtime.txt',$timeS,FILE_APPEND);
        
        // var_dump($timeS);
        // echo '<br>';
        // echo '---------------<br>';
        $timeT = \yii::$app->bjTime->strtotime($timeS);
        $timeT = $timeT+8*3600;
        
       // return '0';
        return \yii::$app->bjTime->date('Y-m-d H:i:s',$timeT);
        
    }
    
    /**
     * 处理相关文件，从中获取数据
     */
    public function dealData()
    {
        
        $this->emailObj = new EmailMarket();
   
        $dealDir = $this->dirPath.$this->FileUnZipName;
        $fileList = scandir($dealDir);

        foreach ($fileList as $curFile) {
            if( !in_array( $curFile, array(".", "..") ) && is_dir($dealDir.'/'.$curFile) ) {
                
                // 遍历相关的数据获取相关的内容
                $dataDir = $dealDir.'/'.$curFile; // 处理的文件加目录
                // 获取分组id值
                $curDataDirArr = explode('_',$curFile);
                // if (count($curDataDirArr)==4) { // 文件夹名包含4部分则为emarsys的老通道
                    // $channel_id = 2;  
                // } else {
                    // $channel_id = 6; 
                // }
                
                $channel_id =  $curDataDirArr[2];
                
                $gid = $curDataDirArr[0]; // 当前处理文件夹所属的分组id值
                
                if (!isset($this->reachChannelDataArr[$gid])) { // 初始化当前分组的数据
                    $this->reachChannelDataArr[$gid] = [];
                    $this->reachChannelDataArr[$gid]['gid'] = $gid;
                    $this->reachChannelDataArr[$gid]['channel'] = $channel_id; // 通道id值
                    $this->reachChannelDataArr[$gid]['emailSendInfo'] = []; // 邮件发送信息
                }
                
                // 点击数据统计
                if (file_exists($dataDir.'/CLICKS.csv')) {
                    // $handleClick = @fopen($dataDir.'/CLICKS.csv','r');
                    // if ($handleClick ) {
                        // $this->readFileClick($handleClick,$gid);
                        // fclose($handleClick);
                    // }
                    
                    $this->readFileClickCsv($dataDir.'/CLICKS.csv',$gid);
                }
                
                // 弹回数据统计
                if (file_exists($dataDir.'/BOUNCES.csv')) {
                    // $handleBounce = @fopen($dataDir.'/BOUNCES.csv','r');
                    // if ($handleBounce) {
                        // $this->readFileBounce($handleBounce,$gid);
                        // fclose($handleBounce);
                    // }
                    $this->readFileBounceCsv($dataDir.'/BOUNCES.csv',$gid);
                }
                
                //  投诉信息统计
                if (file_exists($dataDir.'/COMPLAINTS.csv')) {
                    
                    // $handleComplaint =  @fopen($dataDir.'/COMPLAINTS.csv','r');
                    // if ($handleComplaint) {
                        // $this->readFileComplaint($handleComplaint,$gid);
                        // fclose($handleComplaint);
                    // }
                    
                    $this->readFileComplaintCsv($dataDir.'/COMPLAINTS.csv',$gid);
                }
                
                
                // 退订的数据
                if (file_exists($dataDir.'/UNSUBSCRIBES.csv')) {
                    // $handleUnsubscribes = @fopen($dataDir.'/UNSUBSCRIBES.csv','r');
                    // if ($handleUnsubscribes) {
                        // $this->readFileUnsubscribe($handleUnsubscribes,$gid);
                        // fclose($handleUnsubscribes);
                    // }  
                    
                    $this->readFileUnsubscribeCsv($dataDir.'/UNSUBSCRIBES.csv',$gid);
                }
                
            }
        }

        //跟踪当前进度 author xianxuefeng,date 2018-7-3
        $redis = new RedisSysEmail();
        $json = $redis->get($this->key);
        $schedule = ['current' => 'dealData','syn_completed' => 'false','status'=>'false','msg' =>'通道返回数据写入mysql异常'];
        $info = \GuzzleHttp\json_decode($json,true);

        // 数据入库
        $tableName = 'mail_trace_detail';
       
        $curBjTime = \yii::$app->bjTime->time();

        foreach ($this->reachChannelDataArr as $reachChannelDataArrK => $reachChannelDataArrV) {
            
            $gid = $reachChannelDataArrV['gid'];
            if (isset($info['group_id']) && $info['group_id'] < $gid) {
                continue;
            }
            $schedule['group_id'] = $gid;     //跟踪当前进度 author xianxuefeng,date 2018-7-3
            $redis->set($this->key, \GuzzleHttp\json_encode($schedule));

            // 如果我们网站没有当前分组则不统计
            $groupExistInfoSql =  "select count(*) from mail_group where group_id={$gid}";
            $groupExistInfo = Yii::$app->db->createCommand($groupExistInfoSql)->queryScalar();
            if (!$groupExistInfo) {
                continue;
            }
            
            $channelId = $reachChannelDataArrV['channel'];
            $valuesArr = [];
            $valuesStr = "";
           // click_time
            foreach ($reachChannelDataArrV['emailSendInfo'] as $emailSendInfoK => $emailSendInfoV) {
                
                // 插入相关数据
                $insertSql = "insert into {$tableName}(channel_id,gid,email,email_type,is_hard_bounces,is_soft_bounces,bounces_time,bounces_date,is_complaint,complaint_time,complaint_date,is_unsubscribe,unsubscribe_time,unsubscribe_date,is_click,click_time,click_date,add_time) values " ;
           
                // 信息不存在的则补全默认信息
                
                $emailType = $this->emailObj->getEmailType($this->emailObj->decryption($emailSendInfoV['email']));// 邮箱类型
                $email = $emailSendInfoV['email']; // 邮箱地址
                
                $is_hard_bounces = isset($emailSendInfoV['is_hard_bounces']) ? $emailSendInfoV['is_hard_bounces'] : 0; // 是否硬弹
                
                $is_soft_bounces = isset($emailSendInfoV['is_soft_bounces']) ? $emailSendInfoV['is_soft_bounces'] : 0; // 是否软弹
                
                $bounces_time = ($is_hard_bounces || $is_soft_bounces) && isset($emailSendInfoV['bounces_time']) ? $this->timeDeal($emailSendInfoV['bounces_time']) : 0; // 弹出时间
                
                $bounces_date = $bounces_time ? strstr($bounces_time,' ',true) : '';
                
                $is_complaint = isset($emailSendInfoV['is_complaint']) ? $emailSendInfoV['is_complaint'] : 0; // 是否投诉
                
                $complaint_time = $is_complaint && isset($emailSendInfoV['complaint_time']) ? $this->timeDeal($emailSendInfoV['complaint_time']) : 0; // 投诉时间
                
                $complaint_date = $complaint_time ? strstr($complaint_time,' ',true) : '';
                
                $is_unsubscribe = isset($emailSendInfoV['is_unsubscribe']) ? $emailSendInfoV['is_unsubscribe'] : 0; // 是否退订
                
                $unsubscribe_time = $is_unsubscribe && isset($emailSendInfoV['unsubscribe_time']) ? $this->timeDeal($emailSendInfoV['unsubscribe_time']) : 0; // 退订时间
                
                $unsubscribe_date = $unsubscribe_time ? strstr($unsubscribe_time,' ',true) : '';
                
                $is_click = isset($emailSendInfoV['is_click']) ? $emailSendInfoV['is_click'] : 0; // 是否点击
                
                $click_time = $is_click && isset($emailSendInfoV['click_time']) ? $this->timeDeal($emailSendInfoV['click_time']) : 0; // 点击时间
                
                $click_date = $click_time ? strstr($click_time,' ',true) : '';
                //对记录做唯一性判断
                $dataArr = array(
                    'is_hard_bounces'   => $is_hard_bounces,
                    'is_soft_bounces'   => $is_soft_bounces,
                    'bounces_time'      => $bounces_time,
                    'bounces_date'      => $bounces_date,
                    'is_complaint'      => $is_complaint,
                    'complaint_time'    => $complaint_time,
                    'complaint_date'    => $complaint_date,
                    'is_unsubscribe'    => $is_unsubscribe,
                    'unsubscribe_time'  => $unsubscribe_time,
                    'unsubscribe_date'  => $unsubscribe_date,
                    'is_click'  => $is_click,
                    'click_time'  => $click_time,
                    'click_date'  => $click_date
                );
                $updateData = [];
                foreach($dataArr as $key => $data){
                    if($data){
                        $updateData[] = "$key = '$data'";
                    }
                }
                if(empty($updateData)){
                    continue;
                }
                $valuesStr = "({$channelId},{$gid},'{$email}','{$emailType}',{$is_hard_bounces},{$is_soft_bounces},'{$bounces_time}','{$bounces_date}',{$is_complaint},'{$complaint_time}','{$complaint_date}',{$is_unsubscribe},'{$unsubscribe_time}','{$unsubscribe_date}',{$is_click},'{$click_time}','{$click_date}',{$curBjTime}) ON DUPLICATE KEY UPDATE is_deal=0,channel_id={$channelId},add_time='{$curBjTime}',".join(',',$updateData);
                $insertSql .=$valuesStr;
                // 入库
                Yii::$app->db->createCommand($insertSql)->execute();
            }
           
        }
       
        echo '数据处理完成';
    }
    
    /**
     * 读取Unsubscribe文件
     */
    public function readFileUnsubscribeCsv($filename,$gid)
    {
        $allData =  Yii::$app->pubfun->getCSVdata($filename);
        array_shift($allData);
        if ($allData) {
            foreach ($allData as $bufferArr) {
                if (count($bufferArr) < 3) { // 当前行记录数小于3，说明没有没有记录到邮箱信息
                    continue;
                }
                $email = $this->emailObj->encryption($bufferArr[2]);
                $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                    
                // 说明当前记录是退订
                $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_unsubscribe'] = 1; // 退订

                $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['unsubscribe_time'] = $bufferArr[0]; // 退订时间
            }
        }
    }
    
    public function readFileUnsubscribe($handle,$gid)
    {
        $i=1;
        
        // 循环读取数据
        while (!feof($handle)) {
            $buffer = fgets($handle);
            if ($i==1) {    // 第一行数据不进行处理
                            
                $i++;
                continue;
            } else {
                // 保存邮箱的相关信息
                $bufferArr = explode(',',$buffer);
                if (count($bufferArr) < 3) { // 当前行记录数小于3，说明没有没有记录到邮箱信息
                    continue;
                }
                if ($bufferArr[2]) {
                    
                    // 加密邮箱信息
                    $email = $this->emailObj->encryption($bufferArr[2]);
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                    
                    // 说明当前记录是退订
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_unsubscribe'] = 1; // 退订

                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['unsubscribe_time'] = $bufferArr[0]; // 退订时间
                }
            }
        }   
    }
    
    /**
     * 读取complaint
     */
    public function readFileComplaintCsv($filename,$gid)
    {
        $allData =  Yii::$app->pubfun->getCSVdata($filename);
        array_shift($allData);
        if ($allData) {
            foreach ($allData as $bufferArr) {
                if (count($bufferArr) < 2) { // 当前行记录数小于2，说明没有没有记录到邮箱信息
                    continue;
                }
                // 加密邮箱信息
                $email = $this->emailObj->encryption($bufferArr[1]);
                $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                
                // 说明当前记录是投诉
                $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_complaint'] = 1; // 投诉

                $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['complaint_time'] = $bufferArr[0]; // 投诉时间
            }
        }
    }
    
    public function readFileComplaint($handle,$gid)
    {
       
        $i=1;
        
        // 循环读取数据
        while (!feof($handle)) {
            $buffer = fgets($handle);
            if ($i==1) {    // 第一行数据不进行处理
                            
                $i++;
                continue;
            } else {
                // 保存邮箱的相关信息
                $bufferArr = explode(',',$buffer);
                if (count($bufferArr) < 2) { // 当前行记录数小于2，说明没有没有记录到邮箱信息
                    continue;
                }
                if ($bufferArr[1]) {
                    // 加密邮箱信息
                    $email = $this->emailObj->encryption($bufferArr[1]);
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                    
                    // 说明当前记录是投诉
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_complaint'] = 1; // 投诉

                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['complaint_time'] = $bufferArr[0]; // 投诉时间
                }
            }
        }   
    }
    
    /**
     * 读取文件bounce相关
     */
    public function readFileBounceCsv($filename,$gid)
    {
        $allData =  Yii::$app->pubfun->getCSVdata($filename);
        array_shift($allData);
        if ($allData) {
            foreach ($allData as $bufferArr) {
                if (count($bufferArr) < 3) { // 当前行记录数小于3，说明没有没有记录到邮箱信息
                    continue;
                }
                if ($bufferArr[2]) {
                    // 加密邮箱信息
                    $email = $this->emailObj->encryption($bufferArr[2]);
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                    
                    if ($bufferArr[1] == '1607') { // 说明当前记录是硬弹
                        $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_hard_bounces'] = 1; // 硬弹
                        
                    } elseif ($bufferArr[1] == '1606') { // 说明当前记录是软弹
                        $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_soft_bounces'] = 1; // 软弹
                    }
                   
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['bounces_time'] = $bufferArr[0]; // 弹回时间
                }  
            }
        }
    }
    public function readFileBounce($handle,$gid)
    {
     
        $i=1;
        
        // 循环读取数据
        while (!feof($handle)) {
            $buffer = fgets($handle);
            if ($i==1) {    // 第一行数据不进行处理
                            
                $i++;
                continue;
            } else {
                // 保存邮箱的相关信息
                $bufferArr = explode(',',$buffer);
                if (count($bufferArr) < 3) { // 当前行记录数小于3，说明没有没有记录到邮箱信息
                    continue;
                }
                if ($bufferArr[2]) {
                    // 加密邮箱信息
                    $email = $this->emailObj->encryption($bufferArr[2]);
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                    
                    if ($bufferArr[1] == '1607') { // 说明当前记录是硬弹
                        $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_hard_bounces'] = 1; // 硬弹
                        
                    } elseif ($bufferArr[1] == '1606') { // 说明当前记录是软弹
                        $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_soft_bounces'] = 1; // 软弹
                    }
                   
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['bounces_time'] = $bufferArr[0]; // 弹回时间
                }  
            }
        }
    }
    
    /**
     * 读取文件bounce相关
     */
    public function readFileClickCsv($filename,$gid)
    {
        $allData =  Yii::$app->pubfun->getCSVdata($filename);
        array_shift($allData);
        if ($allData) {
            foreach ($allData as $bufferArr) {
                // 保存邮箱的相关信息
                if (count($bufferArr) < 4) { // 当前行记录数小于4，说明没有没有记录到邮箱信息
                    continue;
                }
                
                if ($bufferArr[3]) {
                   
                    // 加密邮箱信息
                    $email = $this->emailObj->encryption($bufferArr[3]);
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_click'] = 1; // 被点击
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['click_time'] = $bufferArr[0]; // 点击时间
                }  
            }
        }
    }
    
    /**
     * 读取文件click相关
     */
    public function readFileClick($handle,$gid)
    {
       
       
        $i=1;
        
        // 循环读取数据
        while (!feof($handle)) {
            $buffer = fgets($handle);
            if ($i==1) {    // 第一行数据不进行处理
                            
                $i++;
                continue;
            } else {
                // 保存邮箱的相关信息
                $bufferArr = explode(',',$buffer);
                if (count($bufferArr) < 4) { // 当前行记录数小于4，说明没有没有记录到邮箱信息
                    continue;
                }
                
                if ($bufferArr[3]) {
                   
                    // 加密邮箱信息
                    $email = $this->emailObj->encryption($bufferArr[3]);
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email; // 邮箱地址
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_click'] = 1; // 被点击
                    $this->reachChannelDataArr[$gid]['emailSendInfo'][$email]['click_time'] = $bufferArr[0]; // 点击时间
                }  
            }
        } 
    }
    
    /**
     * 解压zip文件
     */
    public function unZip() 
    {
        $zip = new \ZipArchive;
//        var_dump(file_exists($this->dirPath.$this->FileUnZipName));
        
        if (file_exists($this->dirPath.$this->FileUnZipName)) {
            echo ' -- 文件已经解压----';
            return true;
        } else {
            echo '开始解压文件'.$this->downLoadFileName;
            $res = $zip->open($this->dirPath.$this->downLoadFileName);
            if ($res === TRUE)
            {
                $zip->extractTo($this->dirPath);
                $zip->close();
                echo ' -- 解压成功---';
                return true;
            } else {
                $this->msg =  ' -- 解压失败---';
                echo $this->msg;
                return false;
            }
        }
    }  
}

